package com.ys.sboot.hystrix.arch;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * <p>@description:
 * <p>
 * hystrix进行资源隔离,其实是提供更一个抽象,叫做command,就是说，如果要把对某个服务的所有调用请求,全部隔离在同一个资源池内
 * 对这个以来服务的所有调用请求，全部走这个资源池内的资源,不用再去私用其他的资源,这就是叫做资源隔离
 * <p>
 * hystrix 最基本的资源隔离技术==》线程池隔离技术
 * <p>
 * 对某一个依赖服务,商品服务的所有请求,全部隔离到一个线程池内,对商品服务的每次调用请求都更撞到一个command里面
 * 每个command(每次服务调用) 都是使用线程池内的一个线程去执行
 * <p>
 * 当依赖服务=>商品服务，现在同时发起调用量为1000了,但是线程池只有10个线程,最多就只有这十个线程去执行
 * <p>
 * </p>
 *
 * @author yangshuang
 * @version 1.0
 * @date 2018/4/15 下午5:46
 */
public class CommonHelloWorld extends HystrixCommand<String> {


    private final String name;

    public CommonHelloWorld(String name) {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));

        this.name = name;

    }


    @Override
    protected String run() throws Exception {


        String url = "http://127.0.0.1:8082/logBack/reqLogBack?name=" + name;
        CloseableHttpClient httpCilent = HttpClients.createDefault();//Creates CloseableHttpClient instance with default configuration.
        HttpGet httpGet = new HttpGet(url);
        String srtResult = null;
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpCilent.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            try {
                srtResult = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(srtResult);
        } else if (httpResponse.getStatusLine().getStatusCode() == 400) {
            //..........
        } else if (httpResponse.getStatusLine().getStatusCode() == 500) {
            //.............
        }

        return srtResult;
    }
}
